<?php
	####################################################
	# IoFileAndDir 파일 및 이미지 관련                 #
	####################################################

	class IoFileAndDir {

		# 디렉터리 리스트
		public static function dir_list($path = "./") {
			$path = opendir($path);
			while ($list = readdir($path)) if ($list != "." && $list != "..") $arraydir[] = $list;
			closedir($path);
			return $arraydir;
		}

		# 파일이름과 확장자 분리
		public static function explode_file_and_file_ext($filename) {
			$filename = strtolower($filename);
			$elements = explode('.', $filename);
			$elemcnt = count($elements) -1;
			if (count($elements) == 1) $ext = '';
			else $ext = $elements[$elemcnt];
			unset($elements[$elemcnt]);
			$fname = implode($elements, '');
			$fileinfo["name"] = $fname;
			$fileinfo["ext"] = $ext;
			return $fileinfo;
		}

		# 이미지 확장자
		public static function image_type_file_ext($filename) {
			$webimg = IoFileAndDir::explode_file_and_file_ext($filename);
			$webext = $webimg["ext"];
			$defineexp = array("gif", "jpg", "png");
			$count = count($defineexp);
			for ($i = 0; $i < $count; $i++) {
				if ($defineexp[$i] == $webext) return true;
			}
			return false;
		}

		# 마임타입을 리턴
		public static function get_mime_content_type($filename) {
			$mime_types = array(
				'txt' => 'text/plain',
				'htm' => 'text/html',
				'html' => 'text/html',
				'php' => 'text/html',
				'css' => 'text/css',
				'js' => 'application/javascript',
				'json' => 'application/json',
				'xml' => 'application/xml',
				'swf' => 'application/x-shockwave-flash',
				'flv' => 'video/x-flv',

				// images
				'png' => 'image/png',
				'jpe' => 'image/jpeg',
				'jpeg' => 'image/jpeg',
				'jpg' => 'image/jpeg',
				'gif' => 'image/gif',
				'bmp' => 'image/bmp',
				'ico' => 'image/vnd.microsoft.icon',
				'tiff' => 'image/tiff',
				'tif' => 'image/tiff',
				'svg' => 'image/svg+xml',
				'svgz' => 'image/svg+xml',

				// archives
				'zip' => 'application/zip',
				'rar' => 'application/x-rar-compressed',
				'exe' => 'application/x-msdownload',
				'msi' => 'application/x-msdownload',
				'cab' => 'application/vnd.ms-cab-compressed',

				// audio/video
				'mp3' => 'audio/mpeg',
				'qt' => 'video/quicktime',
				'mov' => 'video/quicktime',

				// adobe
				'pdf' => 'application/pdf',
				'psd' => 'image/vnd.adobe.photoshop',
				'ai' => 'application/postscript',
				'eps' => 'application/postscript',
				'ps' => 'application/postscript',

				// ms office
				'doc' => 'application/msword',
				'rtf' => 'application/rtf',
				'xls' => 'application/vnd.ms-excel',
				'ppt' => 'application/vnd.ms-powerpoint',

				// open office
				'odt' => 'application/vnd.oasis.opendocument.text',
				'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
			);

			$ext = strtolower(array_pop(explode('.',$filename)));
			if (array_key_exists($ext, $mime_types)) {
				return $mime_types[$ext];
			} elseif (function_exists('finfo_open')) {
				$finfo = finfo_open(FILEINFO_MIME);
				$mimetype = finfo_file($finfo, $filename);
				finfo_close($finfo);
				return $mimetype;
			} else {
				return 'application/octet-stream';
			}
		}

		# 현재 디렉터리
		public static function nowdir() {
			global $DOCUMENT_ROOT;
			global $PHP_SELF;
			$getdir = pathinfo($DOCUMENT_ROOT.$PHP_SELF);
			return $getdir["dirname"];
		}

		# 업로드
		public static function file_upload($upfile, $upfile_name, $upfile_size, $dir, $newfilename) {
			if ($upfile_size) {
				$is_file = is_file("{$dir}/{$newfilename}");
				if ($is_file) unlink("{$dir}/{$newfilename}");
				move_uploaded_file($upfile, "{$dir}/{$newfilename}");
				chmod("{$dir}/{$newfilename}", 0644);
				return true;
			} else {
				return false;
			}
		}

		# 파일을 쓴다.
		# 의존성 StrFormat
		public static function nfilewriter($filename, $filecontent, $is_rtrim = TRUE) {
			if($is_rtrim){
				$filecontent_put = "";
				$filecontent_put .= StrFormat::multy_line_rtrim($filecontent);
			} else {
				$filecontent_put = $filecontent;
			}
			$handle = fopen($filename, "w+") or die("Couldn't open $filename");
			if(is_array($filecontent)){
				foreach($filecontent as $key=>$val){
					fputs($handle,$val);
				}
			} else {
				fputs($handle,chr(0x01),0);
				fputs($handle,$filecontent_put);

			}
			fclose($handle);
			return TRUE;
		}

		# 파일을 라인단위로 읽는다.
		public static function nfilereader($filename) {
			$fp = fopen( $filename, "r" ) or die("Couldn't open $filename");
			while ( ! feof( $fp ) ) {
				$line = fgets( $fp, 1024 );
				$retarr[] = $line;
			}
			return $retarr;
		}

		# 배열내의 파일을 삭제
		public static function nunlink($filename_arr) {
			foreach($filename_arr as $key=>$val){
				$ret[] = @unlink($val);
			}
			return $ret;
		}

		# 해당 dir의 파일과 디렉터리를 모두 삭제
		public static function rmdir_and_unlink($dir) {
			$dirs = @dir($dir);
			if($dirs) {
				while(false !== ($entry = @$dirs->read())) {
					if(($entry != '.') && ($entry != '..')) {
						if(is_dir($dir.'/'.$entry)) {
							IoFileAndDir::rmdir_and_unlink($dir.'/'.$entry);
						} else {
							@unlink($dir.'/'.$entry);
						}
					}
				}
				$dirs->close();
				@rmdir($dir);
			}
		}

		# 포스다운로드.
		public static function force_download($dir, $file) {
			if ((isset($file))&&(file_exists($dir.$file))) {
				header("Content-type: application/force-download");
				header('Content-Disposition: inline; filename="' . $dir . $file . '"');
				header("Content-Transfer-Encoding: Binary");
				header("Content-length: " . filesize($dir.$file));
				header('Content-Type: application/octet-stream');
				header('Content-Disposition: attachment; filename="' . $file . '"');
				readfile("$dir$file");
			}
		}

		# 디렉터리맵.
		public static function dirmap($source_dir, $directory_depth = 0, $hidden = FALSE) {
			if ($fp = @opendir($source_dir)) {
				$filedata	= array();
				$new_depth	= $directory_depth - 1;
				$source_dir	= rtrim($source_dir, '/').'/';
				while (FALSE !== ($file = readdir($fp))) {
					#디렉터리가 svn일경우
					if($file == '.svn'){
						continue;
					}
					if ( ! trim($file, '.') OR ($hidden == FALSE && $file[0] == '.')) {
						continue;
					}
					if (($directory_depth < 1 OR $new_depth > 0) && @is_dir($source_dir.$file)) {
						if(substr($file,-6,6) != '.files'){
							$filedata[$file] = IoFileAndDir::dirmap($source_dir.$file.'/', $new_depth, $hidden);
						}
					} else {
						//if(substr($file,-4,4) != '.ttx' && substr($file,0,2) != '~$'){
						//if(substr($file,-4,4) != '.ttx' && substr($file,-4,4) != '.xls' && substr($file,0,2) != '~$'){
							$filedata[] = $file;
						//}
					}
				}
				closedir($fp);
				return $filedata;
			}
			return FALSE;
		}

		# 파일사이즈를 얻는다.
		public static function get_size($file) {
			$size = filesize($file);
			if ($size < 0)
				if (!(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'))
					$size = trim(`stat -c%s $file`);
				else{
					$fsobj = new COM("Scripting.FileSystemObject");
					$f = $fsobj->GetFile($file);
					$size = $file->Size;
				}
			return $size;
		}

		# 계정용량 계산
		public static function setDu($key='') {
			$duPath = dirname(__FILE__) . "/../conf/du.php";
			$hostPath = str_replace($_SERVER['SCRIPT_NAME'], "", $_SERVER['SCRIPT_FILENAME']);
			$shopPath = dirname(__FILE__) . "/../";

			if (file_exists($duPath) === false) $mode = 'all';
			else if (date('Ymd', filectime($duPath)) != date('Ymd')) $mode = 'all';
			else if (date('Ymd', filectime($duPath)) == date('Ymd') && $key == '') return;

			@include $duPath;
			if ($mode != 'all' && $key) $dutmp = $du;

			# root 폴더용량 계산
			if ($mode == 'all') $du[root] = intval(`du -sb {$hostPath}`);

			# data 폴더용량 계산
			if ($mode == 'all'){
				$ret = explode(chr(10), `du -hb --max-depth=1 {$shopPath}/data/`); # data
				foreach ($ret as $v){
					$div = explode("\t", $v);
					$div[1] = str_replace("{$shopPath}/data/", "", $div[1]);
					if (strpos($div[1],'/') === false && $div[1]) $du[disks][$div[1]] = $div[0];
				}
			}
			else if (in_array($key, array('board', 'editor', 'goods'))){
				$du[disks][$key] = intval(`du -sb {$shopPath}/data/{$key}/`);
				$du[root] += ($du[disks][$key] - $dutmp[disks][$key]);
			}

			return $du;
		}

		# 파일 사이즈를 kb, mb에 맞추어서 변환해서 리턴
		public static function get_native_file_size($size) {
			if(!$size) return "0 Byte";
			if($size<1024) {
				return ($size." Byte");
			} elseif($size >1024 && $size< 1024 *1024)  {
				return sprintf("%0.1f KB",$size / 1024);
			}
			else return sprintf("%0.2f MB",$size / (1024*1024));
		}

		# 바이트를 스트링으로 계산하여 리턴
		public static function byte2str($k) {
			$x = ($k>1024) ? round($k/1024) : round($k/1024,2);		// K단위
			$y = round($x / 1024);		// M단위

			if ($y>999){
				$x = round($y / 1024,2);
				$s = "G";
			}
			else if ($x>999){
				$x = round($x / 1024,2);
				$s = "M";
			} else $s = "K";
			return $x.$s;
		}

		# mb를 byte로 계산하여 리턴
		public static function mb2byte($x) {
			$x *= 1024 * 1024;
			return $x.$s;
		}

		# md5sum을 만든다.
		function md5sum($str="") {
			if($str=="") {
				$str = uniqid(rand(), true);
			}
			mt_srand((double)microtime()*10000);
			return md5($str);
		}

	}

?>